package com.weishuang.monitor.leader.commons.jwt;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Created by ace on 2017/9/10.
 */
@Component
public class JwtTokenUtil implements CommandLineRunner {

    @Value("${jwt.expire}")
    private int expire;

    @Value("${jwt.rsa-secret}")
    private String secret;

    public static byte[] PUBLIC_KEY;
    public static byte[] PRIVATE_KEY;


    public String generateToken(JWTInfo jwtInfo) throws Exception {
        return JWTHelper.generateToken(jwtInfo, PRIVATE_KEY,expire);
    }

    public JWTInfo getInfoFromToken(String token) throws Exception {
        return JWTHelper.getInfoFromToken(token, PUBLIC_KEY);
    }

    /**
     * Bean 初始化执行。获取秘钥参数生成公钥私钥
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        if (PUBLIC_KEY == null || PRIVATE_KEY == null) {
            Map<String, byte[]> stringMap = RsaKeyHelper.generateKey(secret);
            PUBLIC_KEY = stringMap.get("pub");
            PRIVATE_KEY = stringMap.get("pri");
        }
    }
}
